package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.IYddUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/ydd_user")
public class YddUserController {

    @Autowired
    private IYddUserService iYddUserService;

    @GetMapping("/list")
    public ResultData page(int page, int limit, String username, String mobile, Integer sex){

        //创建分页构建器
        Page<YddUser> yddUserPage = new Page<>(page,limit);
        //创建条件查询器
        LambdaQueryWrapper<YddUser> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(username),YddUser::getUsername,username);
        lqw.like(StringUtils.isNotEmpty(mobile),YddUser::getMobile,mobile);
        lqw.eq(sex != null,YddUser::getSex,sex);
        iYddUserService.page(yddUserPage,lqw);

        Map<String,Object> Map = new HashMap<>();
        Map.put("count",yddUserPage.getTotal());
        Map.put("totalPages",yddUserPage.getPages());
        Map.put("pageSize",yddUserPage.getSize());
        Map.put("currentPage",yddUserPage.getCurrent());
        Map.put("data",yddUserPage.getRecords());

        return ResultData.ok("查询成功",Map);
    }

    /**
     * 添加用户
     * @param yddUser
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody YddUser yddUser){
        yddUser.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        iYddUserService.save(yddUser);
        return ResultData.ok("添加成功",yddUser);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData del(Integer id){
        if (id != null){
            iYddUserService.removeById(id);
            return ResultData.ok("删除成功","");
        }
        return ResultData.error("删除失败");
    }

    /**
     * 数据回显
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(Integer id){
        if (id != null){
            YddUser yddUser = iYddUserService.getById(id);
            return ResultData.ok("获取数据成功",yddUser);
        }
        return ResultData.error("该用户不存在");
    }

    /**
     * 修改用户信息
     * @param yddUser
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody YddUser yddUser){
        iYddUserService.updateById(yddUser);
        return ResultData.ok("修改数据成功",yddUser);
    }



}
